package cn.edu.xidian.controller;

import android.os.Environment;
import android.util.Log;
import cn.edu.xidian.dao.Impl.UserDaoImpl;
import cn.edu.xidian.domain.User;
import cn.edu.xidian.untils.IDUntils;
import cn.edu.xidian.untils.SQLiteUntils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.*;
import java.util.ArrayList;

/**
 * 将数据导入导出操作
 */
public class JsonController {

    private byte[] buffer = null;
    private File file;//声明一个外部对象来存储外部文件
    private ArrayList<User> userList;
    private UserDaoImpl userDaoImpl;

    public JsonController() {
        userDaoImpl = new UserDaoImpl();
    }

    public ArrayList<User> getUserList() {
        return userList;
    }


    //将信息转换为json格式
    public static String transferToJson(User user){
        Gson gson = new Gson();
        String json = gson.toJson(user);

        return json;
    }

    public void importFromPhone(){
        //实例化文件对象，外部存储根目录和文件名称
        file = new File(Environment.getExternalStorageDirectory(),"LostPassJson.json");
        JsonArray site = null;

        //从json文件中读取信息到数据库中
        FileInputStream fis = null;//声明文件输入流对象
        try{
            fis = new FileInputStream(file);//声明输入流
            buffer = new byte[fis.available()];//实例化字节数组
            fis.read(buffer);//从输入流中读取数据
        }catch(FileNotFoundException e)
        {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(fis!=null)
            {
                try{
                    fis.close();//关闭输入流对象
                    String data = new String(buffer);//把字节数组转换为字符串
                    data = data.replaceAll("[\\n\\r]","");

                    //匹配旧版本文本，化为合适的新版本
                    data = data.replaceAll("\\}","\\}\\,");
                    data = data.replaceAll("^\\{","[{");
                    data = data.replaceAll("\\},$","}]");
                    data = data.replaceAll("\\},]","}]");
                    data = data.replaceAll("\"pwd\"","\"user_pwd\"");
                    data = data.replaceAll("\"username\"","\"user_name\"");
                    data = data.replaceAll("\"website\"","\"user_website\"");
                    data = data.replaceAll(",,",",");

                    Log.i("jsonsite",data);

                    JsonElement jsonElement = new JsonParser().parse(data);

                    site = jsonElement.getAsJsonArray();


                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }

        //从json转换回list
        if(site!=null){
            Gson gson = new Gson();
            User user;

            if(userList!=null){//
                userList.clear();
            }else{
                userList = new ArrayList<User>();
            }

            for (JsonElement element : site) {

                user = gson.fromJson(element.toString(),User.class);
                //旧版本没有id
                if(user.getUser_id()==null || "".equals(user.getUser_id())){
                    user.setUser_id(IDUntils.getId());
                }

                Log.i("userjson",user.toString());

                userList.add(user);
            }
        }

        if(userList!=null){
            userDaoImpl.deleteFromdatabase("all");
            userDaoImpl.insertToDatabase(userList.size(),userList);
        }
    }

    public void exportToPhone(){
        //代用数据库相关查询到最新的user列表
        userList = userDaoImpl.getUserList(SQLiteUntils.getSqliteDB());

        //将数据转成json格式
        StringBuilder sb = new StringBuilder("[\n");
        for (User user : userList) {
            sb.append(transferToJson(user)+",\n");
        }
        sb = sb.deleteCharAt(sb.length()-2);
        sb.append("]");
        Log.i("log jsonToFile",sb.toString());

        //保存进手机存储
        //实例化文件对象，外部存储根目录和文件名称
        file = new File(Environment.getExternalStorageDirectory(),"LostPassJson.json");

        //声明文件输出流
        FileOutputStream fos = null;//这里是从app输出到文件
        //jsonToFile保存着完整的json格式信息
        try{
            fos = new FileOutputStream(file);//声明输出流
            fos.write(sb.toString().getBytes());
            fos.flush();
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            if(fos!=null){
                try{
                    fos.close();//关闭输出流
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}
